﻿using BLL.Sgf;
using BLL.Utility;
using Entity.Models;
using Sgf.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Sgf.View
{
    public partial class RegistroDeposito : AbstractPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            UcBotoesCadastro.btnSalvarClick += btnSalvar_Click;
            UcBotoesCadastro.btnLimparCLick += btnLimpar_CLick;
            pnErro.Visible = false;
            
            if (IsPostBack) return;
            PopulaBancos();
        }

        #region -- Botoes --
        private void btnLimpar_CLick(object sender, EventArgs e)
        {
            var campos = new Campos();
            campos.LimparTextBox(this);
        }

        private void btnSalvar_Click(object sender, EventArgs e)
        {
            try
            {
                var pEntity = GetEntity();
                using (var bll = new DepositoBLL())
                {
                    bll.Salvar(pEntity);
                    ExibeMensagem("Operação realizada com sucesso.");
                    btnLimpar_CLick(sender, e);
                }
            }
            catch (EValidationException evx)
            {
                pnErro.Visible = true;
                lbMsg.Text = evx.Message;
            }
            catch (Exception ex)
            {
                throw new Exception("Deposito.aspx.cs.btnSalvar_Click :: " + ex.Message, ex);
            }
        }
        #endregion       

        #region -- Métodos Privados--
        private void PopulaBancos()
        {
            try
            {
                using (var bll = new BancoBLL())
                {
                    ddlBanco.DataSource = bll.BuscaTodos();
                    ddlBanco.DataBind();
                }
                ddlBanco.Items.Insert(0, new ListItem("(Selecione...)", "0"));
            }
            catch (EValidationException evx)
            {
                pnErro.Visible = true;
                lbMsg.Text = evx.Message;
            }
            catch (Exception ex)
            {
                throw new Exception("Deposito.aspx.cs.PopulaBancos :: " + ex.Message, ex);
            }
        }

        private Deposito GetEntity()
        {
            var pEntity = new Deposito
            {
                BancoId = Convert.ToInt32(ddlBanco.SelectedValue),
                Valor = Convert.ToDecimal(txtValor.Text),
                DataDeposito = Convert.ToDateTime(txtDateRecebimento.Text),
                UsuarioId = Convert.ToInt32(Session["UsuarioId"])
            };
            return pEntity;
        }
        #endregion

    }
}